package com.gupao.templatedemo.jdbctemplatedemo;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class JdbcTemplate {

    private DataSource dataSource;

    public JdbcTemplate(DataSource dataSource){
        this.dataSource = dataSource;
    }

    public List<?> executeQuery(String sql,RowMapper rowMapper,Object [] values ){
        try {
            //获取连接
            Connection conn = this.dataSource.getConnection();
            //创建语句集
            PreparedStatement pst = conn.prepareStatement(sql);
            //执行语句集，并且获得结果集
            for (int i=0;i<values.length;i++){
                pst.setObject(i,values[i]);
            }
            ResultSet rs = pst.executeQuery();
            //解析语句集
            List<?> result = this.parseResultSet(rs,rowMapper);
            //关闭结果集
            rs.close();
            //关闭语句集
            pst.close();
            //关闭连接
            conn.close();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    private List<?> parseResultSet(ResultSet rs,RowMapper rowMapper) throws Exception {
        List<Object> result = new ArrayList<>();
        int rowNum = 1;
        result.add(rowMapper.mapRow(rs,rowNum));
        return result;
    }

}
